import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

class HttpDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HttpDemo"),
        elevation: 0.0,
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  @override
  _HttpDemoHomeState createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {

  @override
  void initState() {
    super.initState();

    // fetchPosts().then((value) => print(value));

    /*
    final post = {
      'title': 'hello',
      'descciption': 'nice to meet you.'
    };

    print(post['title']);
    print(post['descciption']);

    // 将 map 类型的数据转换成 json
    final postJson = json.encode(post);
    print(postJson);

    // 将 json 类型的数据 转换成 map
    final postJsonConverted = json.decode(postJson);
    print(postJsonConverted);
    print(postJsonConverted is Map);
    print(postJsonConverted['title']);
    print(postJsonConverted['descciption']);

    print("------------------");
    final postModel = Post.fromJson(postJsonConverted);
    print("title: ${postModel.title}");
    print("title: ${postModel.descciption}");
    print('${json.encode(postModel)}');
    */
  }

  /// 请求服务端数据
  Future<List<Post>> fetchPosts() async {
    final response = await http.get("https://resources.ninghao.net/demo/posts.json");
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      List<Post> posts = responseBody['posts']
        .map<Post> ((item) => Post.fromJson(item))
        .toList();
      // print(posts);
      return posts;
    } else {
      throw Exception("Faild to fetch posts.");
    }
    // print("statusCode: ${response.statusCode}");
    // print("body: ${response.body}");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchPosts(),
      builder: (context, snapshop) {
        print(snapshop.data);
        print(snapshop.connectionState);
        
        if (snapshop.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text("loading..."),
          );
        } else {
          return ListView(
            children: snapshop.data.map<Widget>(
              (item) => ListTile(
                title: Text(item.title),
                subtitle: Text(item.author),
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(item.imageUrl),
                ),
              ),
            ).toList(),
          );
        }
      },
    );
  }
}

class Post {
  final int id;
  final String title;
  final String descciption;
  final String author;
  final String imageUrl;

  Post({
    this.id,
    this.title,
    this.descciption,
    this.author,
    this.imageUrl
  });

  Post.fromJson(Map json) 
    : id = json['id'],
      title = json['title'],
      descciption = json['descciption'],
      author = json['author'],
      imageUrl = json['imageUrl'];

  Map toJson() => {
    'id': id,
    'title': title,
    'descciption': descciption,
    'author': author,
    'imageUrl': imageUrl,
  };
}